import 'package:fish_redux/fish_redux.dart';
import 'package:kunlun_gas/app_files.dart';
import 'action.dart';
import 'state.dart';
import 'dart:io';
import 'package:flutter_location/flutter_location.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:flutter/rendering.dart';
import 'dart:ui';
import 'dart:typed_data';

Effect<PatrolSignInViewState> buildEffect() {
  return combineEffects(<Object, Effect<PatrolSignInViewState>>{
    PatrolSignInViewAction.onSubmit: _onSubmit,
    PatrolSignInViewAction.onTapImage: _onTapImage,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<PatrolSignInViewState> ctx) async {
  LocationData data = await LocationManager.locationManager.getLocation();
  ctx.state.data = data;
}

void _onSubmit(Action action, Context<PatrolSignInViewState> ctx) async {
  if (ctx.state.selectImage == null) return;
  CommonUtils.showWaitLoading(ctx.context);

  ResultData res = await CommonNetWork.uploadImg(ctx.state.selectImage);
  Navigator.pop(ctx.context);
  if (res.success) {
    String signImage = res.data;
    ResultData resultData = await CommonNetWork.staffPatrolStatus(
      workStatus: 2,
      signImage: signImage,
      orderID: ctx.state.info.orderID,
    );
    if (resultData.success) {
      bus.emit('refreshList');
      await CommonUtils.showAlertView(ctx.context, '提交成功');
      Navigator.pop(ctx.context);
    } else
      CommonUtils.showErrorInfo(ctx.context, resultData.desc);
  } else {
    CommonUtils.showErrorInfo(ctx.context, '图片上传失败');
  }
}

void _onTapImage(Action action, Context<PatrolSignInViewState> ctx) async {
  if (ctx.state.selectImage != null) {
    int res =
        await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      ctx.state.selectImage = null;
      ctx.dispatch(PatrolSignInViewActionCreator.onAction());
    } else if (res == 0) {
      CommonUtils.showPhotoAlbumView(
        ctx.context,
        initialIndex: 0,
        galleryItems: <GalleryExampleItem>[
          GalleryExampleItem(
            id: '0',
            resource: ctx.state.selectImage,
          )
        ],
      );
    }
  } else {
    AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
        type: 1, info: ctx.state.info);
    if (imgFile != null) {
      ctx.state.selectImage = imgFile.file;
      ctx.dispatch(PatrolSignInViewActionCreator.onAction());
    }

  }
}
